/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
 * secPaver is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

/*
Package project implements the project parsing.
*/
package project

import (
	"fmt"
	pb "gitee.com/openeuler/secpaver/api/proto/project"
	"gitee.com/openeuler/secpaver/common/utils"
	"github.com/pkg/errors"
	"google.golang.org/protobuf/types/known/structpb"
	"io/ioutil"
	"path/filepath"
	"strings"
)

const (
	MetaFile = "pav.proj"
)

// ParseProjectDir parses the project file and returns the project build information
func ParseProjectDir(dir string) (*pb.ProjectData, error) {
	// parse meta file
	meta, err := parseMeta(filepath.Join(dir, MetaFile))
	if err != nil {
		return nil, errors.Wrapf(err, "fail to parse %s", MetaFile)
	}

	// parse resources definition file
	var res *pb.Resources
	if meta.GetResources() != "" {
		res, err = parseResources(filepath.Join(dir, meta.GetResources()))
		if err != nil {
			return nil, errors.Wrapf(err, "fail to parse %s", meta.GetResources())
		}
	}

	// parse permission definition file
	appList := &pb.ApplicationList{}
	for _, spec := range meta.GetSpecs() {
		app, err := parseSpec(filepath.Join(dir, spec))
		if err != nil {
			return nil, errors.Wrapf(err, "fail to parse %s", spec)
		}

		appList.ApplicationList = append(appList.ApplicationList, app.GetApplicationList()...)
	}

	// parse engine config file
	engineConfMap := make(map[string]*structpb.Struct, 0)
	for _, engConf := range meta.GetEngine() {
		conf, err := parseEngineConfig(filepath.Join(dir, engConf))
		if err != nil {
			return nil, errors.Wrapf(err, "fail to parse engine config %s", engConf)
		}

		engineConfMap[strings.TrimSuffix(engConf, ".json")] = conf
	}

	return &pb.ProjectData{
		Meta:            meta,
		Resources:       res,
		ApplicationList: appList,
		EngineConf:      engineConfMap,
	}, nil
}

func parseMeta(path string) (*pb.Meta, error) {
	meta := &pb.Meta{}
	if err := utils.UnmarshalJSONFileToProto(path, meta); err != nil {
		return nil, err
	}

	return meta, meta.ValidateAll()
}

func parseResources(path string) (*pb.Resources, error) {
	res := &pb.Resources{}
	if err := utils.UnmarshalJSONFileToProto(path, res); err != nil {
		return nil, err
	}

	return res, res.ValidateAll()
}

func parseSpec(path string) (*pb.ApplicationList, error) {
	spec := &pb.ApplicationList{}
	if err := utils.UnmarshalJSONFileToProto(path, spec); err != nil {
		return nil, err
	}
	return spec, spec.ValidateAll()
}

func parseEngineConfig(path string) (*structpb.Struct, error) {
	conf := &structpb.Struct{}

	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("fail to read file")
	}

	if err := conf.UnmarshalJSON(bytes); err != nil {
		return nil, err
	}

	return conf, nil
}
